<template>
  <div class="family-page">
    <van-nav-bar
        title="家庭成员"
        left-arrow
        @click-left="router.back()"
    >
      <template #right>
        <van-icon name="plus" size="18" @click="showAddMember = true" />
      </template>
    </van-nav-bar>

    <!-- 成员列表 -->
    <div class="member-list">
      <van-cell-group>
        <van-swipe-cell
            v-for="member in members"
            :key="member.id"
            :before-close="beforeClose"
        >
          <van-cell
              :title="member.realName"
              :label="`${getRelationLabel(member.relationType)} · ${member.gender === 1 ? '男' : '女'} · ${member.age}岁`"
              @click="handleEdit(member)"
          >
            <template #right-icon>
              <van-tag type="primary" v-if="member.isDefault">默认</van-tag>
            </template>
          </van-cell>
          <template #right>
            <van-button
                square
                type="danger"
                text="删除"
                class="delete-button"
                @click="handleDelete(member)"
            />
          </template>
        </van-swipe-cell>
      </van-cell-group>
    </div>

    <!-- 添加成员弹框 -->
    <van-popup
      v-model:show="showAddMember"
      position="bottom"
      round
      :style="{ height: '70%' }"
    >
      <div class="popup-content">
        <div class="popup-header">
          <div class="popup-title">添加家庭成员</div>
          <van-icon name="cross" @click="showAddMember = false" />
        </div>

        <van-form @submit="onSubmit">
          <van-cell-group inset>
            <!-- 用户ID输入 -->
            <van-field
              v-model="formData.userId"
              name="userId"
              label="用户ID"
              type="number"
              placeholder="请输入用户ID"
              :rules="[{ required: true, message: '请输入用户ID' }]"
            />
<!--            &lt;!&ndash; 姓名输入 &ndash;&gt;-->
<!--            <van-field-->
<!--              v-model="formData.name"-->
<!--              name="name"-->
<!--              label="姓名"-->
<!--              placeholder="请输入姓名"-->
<!--              :rules="[{ required: true, message: '请输入姓名' }]"-->
<!--            />-->
            <van-field
              v-show="false"
              v-model="formData.relation"
              name="relation"
              :rules="[{ required: true, message: '请选择关系' }]"
            />
          </van-cell-group>

          <!-- 关系选择 -->
          <div class="relation-select">
            <div class="relation-title">选择关系</div>
            <div class="relation-grid">
              <div
                v-for="item in relationOptions"
                :key="item.value"
                class="relation-item"
                :class="{ active: formData.relation === item.name }"
                @click="selectRelation(item)"
              >
                <van-icon :name="item.icon" size="24" />
                <span class="relation-name">{{ item.name }}</span>
              </div>
            </div>
          </div>

          <div style="margin: 16px;">
            <van-button round block type="primary" native-type="submit">
              确认添加
            </van-button>
          </div>
        </van-form>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showDialog } from 'vant'
import { getFamilyMembers, addFamilyMember, updateFamilyMember, deleteFamilyMember } from '@/api/family'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()
const router = useRouter()
const members = ref([])
const showAddMember = ref(false)
const showPicker = ref(false)
const isEdit = ref(false)
const currentId = ref(null)

const formData = reactive({
  userId: '',
  name: '',
  relation: ''
})

const relationOptions = [
  { name: '父亲', value: '1', icon: 'manager' },
  { name: '母亲', value: '2', icon: 'user-circle-o' },
  { name: '儿子', value: '3', icon: 'friends' },
  { name: '女儿', value: '4', icon: 'friends' },
  { name: '配偶', value: '5', icon: 'like' },
  { name: '其他', value: '6', icon: 'contact' }
]

// 加载成员列表
const loadMembers = async () => {
  try {
    const { data } = await getFamilyMembers()
    members.value = data
  } catch (error) {
    showToast('获取成员列表失败')
  }
}

// 选择关系
const selectRelation = (item) => {
  formData.relation = item.name
}

// 提交表单
const onSubmit = async () => {
  try {
    await addFamilyMember({
      userId: formData.userId,
      name: formData.name,
      relation: formData.relation,
      relationType: relationOptions.find(item => item.name === formData.relation)?.value
    })
    showToast('添加成功')
    showAddMember.value = false
    formData.userId = ''
    formData.name = ''
    formData.relation = ''
    loadMembers()
  } catch (error) {
    showToast('添加失败：' + error.message)
  }
}

// 编辑成员
const handleEdit = (member) => {
  isEdit.value = true
  currentId.value = member.id
  formData.name = member.name
  formData.relation = member.relationship
  showAddMember.value = true
}

// 删除成员
const handleDelete = async (member) => {
  try {
    await showDialog({
      title: '确认删除',
      message: `确定要删除 ${member.name} 吗？`,
      showCancelButton: true
    })

    await deleteFamilyMember(member.id)
    showToast('删除成功')
    loadMembers()
  } catch (error) {
    if (error !== 'cancel') {
      showToast('删除失败')
    }
  }
}

// 滑动删除确认
const beforeClose = ({ position, instance }) => {
  if (position === 'right') {
    instance.close()
  }
}

// 获取关系标签
const getRelationLabel = (relationType) => {
  const relation = relationOptions.find(item => item.value === relationType)
  return relation ? relation.name : '未知关系'
}

onMounted(() => {
  loadMembers()
})
</script>

<style lang="scss" scoped>
.family-page {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-top: 46px;

  .member-list {
    margin-top: 12px;
  }

  .delete-button {
    height: 100%;
    width: 65px;
    color: #fff;
  }

  .popup-content {
    height: 100%;
    display: flex;
    flex-direction: column;
  }

  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    border-bottom: 1px solid #ebedf0;
  }

  .popup-title {
    font-size: 16px;
    font-weight: 500;
  }

  .relation-select {
    margin: 16px;
    padding: 16px;
    background: #fff;
    border-radius: 8px;
  }

  .relation-title {
    margin-bottom: 16px;
    color: #323233;
    font-size: 14px;
  }

  .relation-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 12px;
  }

  .relation-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 16px 8px;
    background: #f7f8fa;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s;
  }

  .relation-item.active {
    background: #e1f0ff;
    color: #1989fa;
  }

  .relation-name {
    margin-top: 8px;
    font-size: 14px;
  }

  .relation-item:active {
    opacity: 0.8;
  }
}
</style>
